<?php

namespace app\api\controller\master\edition;



use app\api\model\ConstructionNode;
use app\api\model\Detailed;
use app\api\model\DetailedCategory;
use app\api\model\DetailedOption;
use app\api\model\DetailedOptionValue;
use app\api\model\OrderModel;
use app\api\model\PollingModel;
use app\api\model\QuotationListOperation;
use app\api\model\WorkProcess;
use app\api\model\Aliyunoss;
use think\Controller;
use think\Db;
use think\Request;
use think\Exception;
use app\api\model\Common as CommonModel;
use app\api\model\Capital;
use app\api\model\House;
use app\api\validate;


/**
 * 用户端公共接口
 */
class Common extends Controller
{
    
    protected static $user;
    
    public function _initialize()
    {
//        header("Access-Control-Allow-Origin: *"); // 允许任意域名发起的跨域请求
        //self::$user = $this->check_authority();
    }
    
    
    /**
     * @param array $data
     * @return array
     * $data=['id','name'=>'123']  id必填，name选填，默认值为123（有默认值时key不能为int）
     */
    public function post(array $data)
    {
        if (empty($data)) {
            r_date([], 300, '提交数据不正确');
        }
        $return = [];
        foreach ($data as $key => $item) {
            if (!is_int($key)) {
                $val = Request::instance()->post($key);
                if (isset($val)) {
                    $return[$key] = trim($val);
                } else {
                    $return[$key] = trim($item);
                }
            } else {
                $val = Request::instance()->post($item);
                if (!isset($val)) {
                    jso_data([], 300, "缺少 $item 数据");
                }
                $return[$item] = trim($val);
            }
        }
        return $return;
    }
    
    
    /**
     * 检测用户登录和权限
     */
    public function check_authority()
    {
        $access_token = Request::instance()->header("access-token");
        $access_token = empty($access_token) ? input("post.access_token") : $access_token;
        
        if (empty($access_token)) {
            jso_data([], 401, '您还未登录账号，请先登录');
        }
        $user = db('user')->where(['access_token' => $access_token])->find();
        
        if (empty($user)) {
            jso_data([], 401, '账号已下线，请重新登录');
        }
        if ($user['status'] == 1) {
            jso_data([], 300, '请等待审核');
        }
        if ($user['status'] == 3) {
            jso_data([], 300, '该用户已冻结');
        }
        return $user;
    }
    
    /**
     * 发布订单
     * cate_id 二级id
     */
    public function send_need(OrderModel $orderModel, House $house)
    {
        
        $data           = Request::instance()->param();
        $Order_Validate = new validate\Order_Validate();
        if (!$Order_Validate->check($data)) {
            
            jso_data([], 300, $Order_Validate->getError());
        }
        db()->startTrans();
        try {
            $city_id  = 0;
            $province = 0;
            $county   = 0;
            if ($data['province_id']) {
                $province = db('province')->where(['province' => ['like', "%{$data['province_id']}%"]])->value('province_id');
            }
            if ($data['city_id']) {
                $city_id = db('city')->where(['city' => ['like', "%{$data['city_id']}%"], 'province_id' => $province])->value('city_id');
            }
            if ($data['county_id']) {
                $county = db('county')->where(['county' => ['like', "%{$data['county_id']}%"], 'city_id' => $city_id])->value('county_id');
            }
            
            if ($data['channel_details'] == 102 || $data['channel_details'] == 100 || $data['channel_details'] == 96) {
                $time = time();
            } else {
                $time = '';
            }
            $content = 0;
            if ($city_id != 0) {
                $content = $orderModel->UrbanAccess($city_id);
            }
            $house = $house->getHouse(['province' => $province, 'city' => $city_id, 'area' => $county, 'communityName' => $data['communityName'], 'address' => $data['addres'], 'latitude' => $data['lat'], 'longitude' => $data['lng']]);
            if ($content == 0) {
                $order = db('order');
            } else {
                $order = Db::connect($content)->table('order');
            }
            $hematopoiesis = 1;
            $attribution = db('chanel')->where('id', $data['channel_id'])->value('large_category');
            if ($attribution == 5) {
                $attribution = 4;
            }elseif ($attribution==2){
                $attribution = 3;
            }elseif ($attribution==3){
                $attribution = 3;
            }
            $created_time=time();
            $res = $order->insertGetId(['channel_id' => $data['channel_id'],//渠道
                'channel_details' => $data['channel_details'],//渠道
                'order_no' => order_sn(),//订单号
                'pro_id' => $data['pro_id'],//一级问题
                'province_id' => $province,//省
                'city_id' => $city_id,//市
                'county_id' => $county,//区
                'wechat_id' => isset($data['wechat'])?$data['wechat_id']:'',//市
                'addres' => $data['addres'],//地址
                'contacts' => $data['contacts'],//联系人
                'telephone' => $data['telephone'],//联系电话
                'remarks' => $data['remarks'],//备注
                'residential_quarters' => $data['communityName'],//备注
                'logo' => !empty($data['logo']) ? serialize(json_decode($data['logo'], true)) : '',//图片
                'street' => $data['street'],
                'building' => $data['building'],
                'unit' => $data['unit'],
                'room' => $data['room'],
                'state' =>-1,//待指派
                'created_time' => $created_time,//创建时间
                'update_time' => time(),//创建时间
                'lat' => $data['lat'],//创建时间
                'lng' => $data['lng'],//创建时间
                'notcost_time' => $time,//创建时间
                'entry' => '师傅录入-' . $data['username'],//创建时间
                'house_id' => $house,//创建时间
                'hardbound' => $data['hardbound'],//创建时间
                'entry_user_id' => $data['entry_personnel'],//创建时间
                'entry_type' => 2,//创建时间
                'hematopoiesis' => $hematopoiesis,
                'attributions' => $attribution,
            ]);
            
            (new PollingModel())->Alls($res, 0, 0, time(), time());
            $resp_pers = respPers($data['channel_details']);
//            else {
                db('biz_flw')->insert(['order_id' => $res, 'flw_time' => $created_time+60*15, 'resp_pers' => $resp_pers['data'], 'create_time' => $created_time,'update_time' => $created_time]);
            db()->commit();
            json_decode(sendOrder($res), true);
            jso_data([], 200, '新增成功');
        } catch (Exception $e) {
            db()->rollback();
            jso_data(null, 300, $e->getMessage());
        }
        
    }
    /*
     * 可用戒掉列表
     */
    public function ItemLending(CommonModel $common)
    {

        $request           = Request::instance()->param();
        $dataStr    = u8queryForOther($request['invclasscode'], $request['store_id']);
        $data = json_decode($dataStr, true);

        if ($data['status'] !== 'success' || empty($data['data'])) {
            return r_date(null, 200); // 直接返回空结果
        }

        $list = $data['data'];

        // 2. 提取批量处理所需的参数，建立索引映射
        $pkCorps = [];
        $indexMap = []; // 记录原数组索引与关键参数的映射
        foreach ($list as $k => $value) {
            $pkCorp = $value['pk_corp'] ?? '';
            $invClasscode = $value['invcode'] ?? '';
            if (!empty($pkCorp) && !empty($invClasscode)) {
                $pkCorps[] = $pkCorp;
                $indexMap[$k] = [
                    'pk_corp' => $pkCorp,
                    'invclasscode' => $invClasscode,
                    'nonhandnum' => $value['nonhandnum'] ?? 0
                ];
            }
        }

        // 3. 批量查询 u8c_corp 的 store_id（1次查询替代 N 次）
        $pkCorpStoreMap = [];
        if (!empty($pkCorps)) {
            $pkCorpStoreMap = Db::connect(config('database.zong'))
                ->table('u8c_corp')
                ->whereIn('pk_corp', array_unique($pkCorps))
                ->column('store_id', 'pk_corp'); // 格式：[pk_corp => store_id, ...]

        }

        // 4. 批量查询 store_megre 合并信息（1次查询替代 N 次）
        $storeIds = array_filter(array_values($pkCorpStoreMap)); // 过滤空store_id
        $storeMergeMap = [];
        if (!empty($storeIds)) {
            $storeMergeMap = Db::connect(config('database.zong'))
                ->table('store_megre')
                ->where('state', 1)
                ->whereIn('store_id', array_unique($storeIds))
                ->order('id', 'desc')
                ->column('m_store_id', 'store_id'); // 格式：[原store_id => 合并后store_id, ...]

        }

        // 5. 按「实际store_id + invclasscode」分组，避免重复计算
        $calcGroups = [];
        foreach ($indexMap as $k => $item) {
            $originalStoreId = $pkCorpStoreMap[$item['pk_corp']] ?? '';
            if (empty($originalStoreId)) {
                continue;
            }
            // 处理店铺合并，获取实际用于查询的store_id
            $actualStoreId = $storeMergeMap[$originalStoreId] ?? $originalStoreId;
            $invClasscode = $item['invclasscode'];
            // 生成唯一分组键（确保相同条件只计算一次）
            $groupKey = $actualStoreId . '|' . $invClasscode;
            $calcGroups[$groupKey]['params'] = [
                'store_id' => $actualStoreId,
                'invclasscode' => $invClasscode
            ];
            $calcGroups[$groupKey]['indexes'][] = $k; // 记录该分组对应的原数组索引
        }

        // 6. 批量计算每个分组的 materialCount（核心优化）
        $materialCountMap = [];
        foreach ($calcGroups as $group) {
            $params = $group['params'];
            $storeId = 4;
            $invClasscode = $params['invclasscode'];

            // 6.1 批量查询 order_id（复用原逻辑）
            $orderIds = db('order')->where('store_id', $storeId)->whereIn("state", [4, 7])->where('order.cleared_time is  null or order.cleared_time =0')->column('order_id');

            // 6.2 批量计算 material_usage 总和（复用原逻辑）
            $materialUsage = 0;
            if (!empty($orderIds)) {
                $materialUsage = db('material_usage')
                    ->join('order', 'order.order_id = material_usage.order_id', 'left')
                    ->where('code', $invClasscode)
                    ->where('material_usage.status', 0)
                    ->whereIn('order.order_id', $orderIds)
                    ->group('code')
                    ->sum('square_quantity');
            }

            // 6.3 批量计算 secondment 总和（修复原逻辑的 whereIn 错误）
            $secondment = db('secondment')
                ->where('code', $invClasscode)
                ->whereIn('status', [0, 3])
                ->where('lender_store_id', $storeId) // 原代码误写为 whereIn（单个值用where）
                ->sum('number');

            // 6.4 合并结果并映射到所有相关索引
            $total = bcadd($materialUsage, $secondment, 2);
            foreach ($group['indexes'] as $k) {
                $materialCountMap[$k] = $total;
            }
        }

        // 7. 循环赋值（仅内存操作，无数据库查询）
        foreach ($list as $k => $value) {
            $materialCount = $materialCountMap[$k] ?? 0;
            $list[$k]['nonhandnum'] = bcsub(
                $value['nonhandnum'] ?? 0,
                $materialCount,
                2
            );
        }

        jso_data($list, 200, '新增成功');
    }
    /*
    * 获取配置清单
    */
    public function newDetailedList(DetailedCategory $detailedCategory)
    {
        $data = Request::instance()->param();
        $group        = $data['group'];
        $detailedList = $detailedCategory
            ->where('detailed_category.is_enable', 1);
        if ($data['type'] == 0) {
            $detailedList->where('is_agency', 0)
                ->with(['detailedList' => function ($query) use ($group) {
                    $query->where('detailed.groupss', $group);
                }]);
        } else {
            $detailedList->where('is_agency', 1)
                ->where('id', '<>', 22)
                ->with(['detailedList']);
        }
        
        $detailedLists = $detailedList->order('detailed_category.sort desc')->select();;
        foreach ($detailedLists as $k => $ite) {
            if (!empty($ite['detailed_list'])) {
                foreach ($ite['detailed_list'] as $l => $value) {
                    $value['title']      = $ite['title'];
                    $value['isWarranty'] = 1;
                    if (!empty($value['warrantYears']) && $value['warrantYears'] != '0.00') {
                        $value['warranty'] = [
                            'warrantYears' => $value['warrantYears'],
                            'warrantyText1' => $value['warrantyText1'],
                            'exoneration' => $value['exoneration'],
                        ];
                    } else {
                        $value['warranty']   = null;
                        $value['isWarranty'] = 0;
                    }
                    
                    $value['types']    = 4;
                    $value['group']    = $value['groupss'];
                    $detailedListValue = $value->detailedListValue;
                    if (!empty(array_column($detailedListValue, 'option_value_title'))) {
                        $value['detailedListValues'] = $value['detailed_title'] . ',' . implode(array_column($detailedListValue, 'option_value_title'), ',');
                        
                    } else {
                        $value['detailedListValues'] = $value['detailed_title'];
                    }
                    unset($value->detailedListValue, $value['warrantYears'], $value['warrantyText1'], $value['exoneration'], $value['groupss']);
                }
                
            }
            
            if ($ite['id'] == 0) {
                $detailedLists[$k]['detailed_list'] = isset($detailedListList) ? $detailedListList : [];
            }
            
            unset($detailedLists[$k]['sort'], $detailedLists[$k]['is_enable'], $detailedLists[$k]['created_at'], $detailedLists[$k]['updated_at'], $detailedLists[$k]['type'], $detailedLists[$k]['is_agency'], $detailedLists[$k]['condition']);
        }
        
        jso_data($detailedLists, 200, '新增成功');
    }
    
    /*
     * 获取报价配置选项
     */
    public function getDetailedOption(DetailedOption $detailedOption)
    {
        $data = Request::instance()->param();
        $getOptionValue['list'] = $detailedOption
            ->with(['detailedListOptionValues' => function ($query) use ($data) {
                $query->where('detailed_option_value.detailed_id', $data['id'])->group('detailed_option_value.option_value_id');
            }])
            ->where('condition', '<>', 2)
            ->order('option_id desc')
            ->select();
        $detailed_option_sort   = db('detailed_option_sort', config('database.zong'))->where('detailed_id', $data['id'])->select();
        
        foreach ($getOptionValue['list'] as $k => $value) {
            if ($detailed_option_sort) {
                foreach ($detailed_option_sort as $item) {
                    if ($item['option_id'] == $value['option_id']) {
                        $value['sort'] = $item['sort'];
                    }
                    
                }
                
            }
            if (!empty($value['detailed_list_option_values'])) {
                $value['sort']           = isset($value['sort']) ? $value['sort'] : 0;
                $getOptionList['list'][] = $value;
            }
        }

      
        if (isset($getOptionList['list'])) {
            $getOptionList['list'] = $this->arraySort($getOptionList['list'], 'sort', SORT_ASC);
        }
        $detailed                 = db('detailed')->join('unit', 'unit.id=detailed.un_id')->where('detailed_id', $data['id'])->field('rmakes,unit.title')->find();
        $getOptionList['remarks'] = $detailed['rmakes'];
        $getOptionList['title']   = $detailed['title'];
        
        jso_data($getOptionList, 200, '新增成功');
    }
    
    /*
     * 计算价格
     */
    public function getValuation(DetailedOptionValue $detailedOptionValue, CommonModel $common, Capital $capital)
    {
        $data = Request::instance()->param();
        if ($data['types'] == 4 || $data['types'] == 1) {
            $detailedValue = $common->newCapitalPrice($detailedOptionValue, $data['id'], json_decode($data['data'], true));
            if (!$detailedValue['code']) {
                r_date([], 300, $detailedValue['msg']);
            }
            $detailedValueList = $detailedValue['data'];
        } else {
            if ($data['types'] == 0) {
                $product_chan               = db('product_chan')->where('product_id', $data['id'])->find();
                $detailedValueList['sum']   = $product_chan['prices'];
                $detailedValueList['price'] = $product_chan['price_rules'];
                $detailedValueList['unit']  = $product_chan['price_rules'];
                
            } elseif ($data['types'] == 2) {
                $capitalIdFind              = $capital->QueryOne($data['capital_id']);
                $detailedValueList['sum']   = $capitalIdFind['un_Price'];
                $detailedValueList['price'] = [];
                $detailedValueList['unit']  = $capitalIdFind['company'];
                
            }
        }
        jso_data(['price' => $detailedValueList['sumMast'], 'artificial' => $detailedValueList['artificial'], 'unTitle' => $detailedValueList['unit']], 200);
    }
    /*
     * 工艺说明
     */
    public function Processdescription(Detailed $Detailed)
    {
        
        $data = Request::instance()->param();
        $op   = json_decode($data['optionId'], true);
        
        $list                 = $Detailed
            ->with(['detailedListValue'])
            ->where('detailed_id', $data['id'])
            ->find();
        $option_value_title   = [];
        $craft                = [];
        $material             = [];
        $listData['bigTitle'] = $list['detailed_title'];
        $detailed_list_value  = $list['detailed_list_value'];
        foreach ($list['detailed_list_value'] as $list) {
            foreach ($op as $o) {
                if ($list['option_value_id'] == $o) {
                    if (!empty($list['option_value_title'])) {
                        $option_value_title[] = $list;
                    }
                    if (!empty($list['craft'])) {
                        $craft[] = $list;
                    }
                    if (!empty($list['material'])) {
                        $material[] = $list;
                    }
                }
                
            }
            
        }
        $listData['title']    = implode(array_column($option_value_title, 'option_value_title'), '/');
        $listData['craft']    = empty(array_column($craft, 'craft')) ? null : array_column($craft, 'craft');
        $listData['material'] = empty(array_column($material, 'craft')) ? null : array_column($material, 'material');
        jso_data($listData, 200);
    }
    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys 要排序的键字段
     * @param string $sort 排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
    public function user_id($order_id)
    {
        $m = db('order')->alias('a')->field('a.order_id,us.store_id')->join('user us', 'a.assignor=us.user_id', 'left')->where(['a.order_id' => $order_id])->find();
        return $m;
    }
    
    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 师傅端沟通记录
     */
    public function gou()
    {
        $data = Request::instance()->param();
        $re   = db('through')->insertGetId(['mode' => "其它", 'amount' => 0, 'role' => $data['role'], 'remar' => $data['remar'], 'order_ids' => $data['order_ids'], 'baocun' => 0, 'gid' => $data['gid'], 'th_time' => $data['th_time'],]);
        
        if ($re) {
            jso_data([], 200, '新增成功');
        }
        jso_data([], 300);
        
    }
    
    public function u8c()
    {
        $data = Request::instance()->param();
        U8cMasters($data['explanation'], $data['money'], $data['orderId'], 23, 2);
        
        jso_data([], 200, '新增成功');
    }
    
    /**
     * 获取费用已选列表
     */
    public function get_reimbursement_list()
    {
        $data = Request::instance()->post();
        //费用报销
        if ($data['type'] == 1) {
            $reimbursement = db('reimbursement')->where(['order_id' => $data['order_id'], 'type' => 1])->field('reimbursement_name,money,voucher,created_time,id,status,remake, content as remarks,classification')->select();
        } else {
            $reimbursement = db('reimbursement')->where(['order_id' => $data['order_id'], 'type' => 2, 'user_id' => $data['user_id']])->field('reimbursement_name,money,voucher,created_time,id,status,remake,user_id,content as remarks,classification')->order('status asc')->select();
            foreach ($reimbursement as $k => $item) {
                $reimbursement[$k]['user_id'] = Db::connect(config('database.db2'))->table('app_user')->where('id', $item['user_id'])->field('username')->find()['username'];
            }
        }
        foreach ($reimbursement as $k => $item) {
            $reimbursement[$k]['voucher'] = empty(unserialize($item['voucher'])) ? [] : unserialize($item['voucher']);
        }
        
        jso_data($reimbursement, 200);
    }
    
    /**
     * 获取已选列表
     */
    public function get_Material_list()
    {
        $data = Request::instance()->post();
        //材料领用
        $material_usage = db('material_usage')->where(['order_id' => $data['order_id'], 'types' => $data['type']])->field('Material_id,material_name,type,square_quantity,total_price,company,unit_price,created_time,id,status,remake')->order('status asc')->select();
        
        jso_data($material_usage, 200);
    }
    
    /**
     * 获取标题
     */
    public function Material()
    {
        $data = Request::instance()->post();
        $code = empty($data['code']) ? null : $data['code'];
        $data = ClassificationQueryMaterial(2, $data['assist'], $code,$data['user_id'],2);
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = $data['data'];
            foreach ($list['datas'] as $k=>$value){
                $list['datas'][$k]['price']='*';
            }
        } else {
            $list = null;
        }
        
        jso_data($list, 200);
    }
    
    /**
     * 获取列表
     */
    public function Material_list(CommonModel $common)
    {
        $da = Request::instance()->post();
        
        $user = $this->user_id($da['order_id']);
        $code = empty($da['code']) ? null : $da['code'];
        $data = u8cInvcDetail($da['invclasscode'], $user['store_id'], 1, 200, null, 2, $da['assist'], $code,$da['user_id'],2);
        $data = json_decode($data, true);
        if ($data['status'] == 'success') {
            $list = $data['data'];
            $invclcodes = array_column($list, 'invclcode');
            $pendingCounts  = $common->materialsPendingReview($user['store_id'], $invclcodes);
            // 2.3 循环赋值（仅内存操作，高效）
            foreach ($list as &$item) {
                $item['price'] = '*';
                // 恢复 nabnum 计算（使用批量查询的结果）
                $invclcode = $item['invclcode'] ?? '';
                $item['nabnum'] = bcsub(
                    $item['nabnum'] ?? 0,
                    $pendingCounts[$invclcode] ?? 0,
                    2
                );
                   $item['nabnums'] = $pendingCounts[$invclcode]??0;
            }
        } else {
            $list = null;
        }
        
        jso_data($list, 200);
    }
    
    public function addres(OrderModel $orderModel)
    {
        
        $data = Request::instance()->post();
        $re   = $orderModel->addres($data['order_id']);
        
        jso_data($re, 200);
    }
    
    /**
     * 获取库存列表
     */
    public function Stock_list_search()
    {
        
        $da = Request::instance()->post();
        
        $user = $this->user_id($da['order_id']);;
        
        $data = u8cInvcDetail(null, $user['store_id'], 1, 200, isset($da['invname']) ? $da['invname'] : null, 2,0,null,$da['user_id'],2);
        $data = json_decode($data, true);
        
        if ($data['status'] == 'success') {
            $list = $data['data'];
            foreach ($list as $k=>$value){
                $list[$k]['price']='*';
            }
        } else {
            $list = null;
        }
        
        jso_data($list, 200);
    }
    
    //材料费用提交
    public function material_usage()
    {
//        jso_data(null, 300,'盘点暂停领用');
        $data           = Request::instance()->post();
        $material_usage = json_decode($data['materialJson'], true);
        db()->startTrans();
        try {
            
            $p = 0;
            $id=[];
            foreach ($material_usage as $datum) {
                if($datum['square_quantity']==0){
                    throw new Exception('材料领取数量不能为0');
                }
                $square_quantity=db('material_usage')->where('order_id', $data['order_id'])->where('status',1)->where('code', $datum['Material_id'])->sum('square_quantity');
                if($datum['square_quantity']<0){
                    if ($square_quantity<abs($datum['square_quantity'])) {
                        throw new Exception('退回数量超出了本单领用的数量，无法退回，请核对数量后正确退回本单没有领用该材料，无法退回');
                    }
                }
                $pp = ['order_id' => $data['order_id'], 'material_name' => $datum['material_name'], 'Material_id' => 0, 'square_quantity' => $datum['square_quantity'], 'unit_price' => $datum['unit_price'], 'type' => $datum['type'], 'company' => $datum['company'], 'total_price' => round($datum['unit_price'] * $datum['square_quantity'], 2), 'user_id' => $data['user_id'], 'created_time' => time(), 'types' => 2, 'status' => 0, 'shopowner_id' => $data['shopowner_id'], 'total_profit' => $datum['unit_price'] * $datum['square_quantity'], 'code' => $datum['Material_id'], 'invclasscode' => $datum['invclasscode']];
                
                $material_usage = db('material_usage')->insertGetId($pp);
                $id[]=$material_usage;
                db('usage_record')->insertGetId(['id' => $material_usage, 'type' => $datum['type'], 'user_id' => $data['user_id'], 'number' => $datum['square_quantity'], 'created_time' => time(), 'order_id' => $data['order_id'], 'original_number' => $datum['square_quantity'], 'unified' => $datum['Material_id']]);
                
                $p += $pp['total_price'];
                
            }
            $order_setting = db('order_setting')->where('order_id', $data['order_id'])->find();
             if ($data['business_type'] == 2 && $order_setting['stop_material_usage'] == 0) {
                $keyss     = db('sys_config', config('database.zong'))->where('keyss', 'agent_material_code')->value('valuess');
                $capital = db('capital')->where('types', 1)->where('enable', 1)->where('ordesr_id', $data['order_id'])->where('agency',  0)->sum('base_contract_price');
                $moneyList = db('reimbursement')->where('order_id', $data['order_id'])->where('status', '<>', 2)->where('classification', '<>', 4)->sum('money');
                $material_usageSUm = db('material_usage')->whereNotIn('invclasscode', $keyss)->where('order_id', $data['order_id'])->whereNotIn('id',$id)->where('status', '<>', 2)->sum('total_price');
                if (bcadd(bcadd($material_usageSUm, $moneyList, 2), $p, 2) > $capital) {
                    throw new Exception('可使用发包价余额为:' . bcsub($capital, bcadd($material_usageSUm, $moneyList, 2), 2) . ':当前提交金额为:' . $p . '，已超出，请更改或删减。');
                }
            }
            db()->commit();
            jso_data(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            jso_data(null, 300, $e->getMessage());
        }
        
    }
    
    /*
     * 费用报销
     */
    public function reimbursement()
    {
        $data = Request::instance()->post();
        db()->startTrans();
        try {
            if (empty($data['order_id'])) {
                throw new Exception('订单ID不能为空');
            }
            if (empty($data['img'])) {
                throw new Exception('报销图片不能为空');
            }
            if (empty($data['user_id'])) {
                throw new Exception('师傅ID错误');
            }
            if (empty($data['name'])) {
                throw new Exception('请输入报销名称');
            }
            if (empty($data['money'])) {
                throw new Exception('请输入报销金额');
            }
            if (empty($data['remarks'])) {
                throw new Exception('请输入费用说明');
            }
            if ($data['type'] == -1) {
                throw new Exception('请输入报销类型');
            }
            $my_string = explode(',', str_replace('"', '', trim($data['img'], '"[""]"')));
            $op        = ['order_id' => $data['order_id'], 'reimbursement_name' => $data['name'], 'money' => $data['money'], 'voucher' => !empty($data['img']) ? serialize($my_string) : '', 'created_time' => time(), 'user_id' => $data['user_id'], 'status' => 0, 'type' => 2, 'content' => $data['remarks'], 'classification' => $data['type'],];
            
            db('reimbursement')->insert($op);
            db()->commit();
            jso_data(null, 200);
        } catch (Exception $e) {
            db()->rollback();
            jso_data(null, 300, $e->getMessage());
            
        }
        
        
    }
    
    /*
     * 支付详情
     */
    public function CommonMoney($order_id)
    {
        $data   = Request::instance()->post();
        $Common = \app\api\model\Common::order_for_payment($data['order_id']);
        jso_data($Common, 200, '新增成功');
    }
    
    /*
     * 查看沟通记录
     */
    public function cha()
    {
        
        $data = $this->post(['page' => 1, 'limit' => 10, 'order_id', 'role', 'gid']);
        
        $us = db('through')->field('remar,role,th_time,order_ids,url,log,gid');
        if (!empty($data['role'])) {
            $us->where('role', $data['role']);
        }
        if (!empty($data['gid'])) {
            $us->where('gid', $data['gid']);
        }
        $l = $us->where('order_ids', $data['order_id'])->page($data['page'], $data['limit'])->select();
        
        foreach ($l as $k => $v) {
            
            if ($v['url']) {
                
                $l[$k]['url'] = unserialize($v['url']);
            } else {
                $l[$k]['url'] = '';
            }
            if ($v['log']) {
                $l[$k]['log'] = unserialize($v['log']);
            } else {
                $l[$k]['log'] = '';
            }
        }
        
        
        jso_data($l, 200);
    }
    
    /*
     * 查看付款详情
     */
    public function Receivables()
    {
        
        $data = $this->post(['order_id']);
        $us   = db('order')->field('order.ification,order.telephone,co.con_time,order.pro_id2,u.store_id')->join('contract co', 'order.order_id=co.orders_id', 'left')->join('user u', 'order.assignor=u.user_id ', 'left')->where('order_id', $data['order_id'])->find();
        
        $l             = OrderModel::offer($data['order_id']);
        $l['yu']       = (string)$l['yu'];
        $l['con_time'] = $us['con_time'];
        $l['store_id'] = $us['store_id'];
        $l['amount']   = (string)$l['amount'];
        $l['agency']   = (string)$l['agency'];
        $l['man']      = (string)$l['man'];
        $l['data']     = $capital = db('capital')->where(['ordesr_id' => $data['order_id'], 'types' => 1, 'enable' => 1])->field('capital_id,class_a,class_b,company,square,un_Price,zhi,to_price,crtime,labor_cost,increment,cooperation')->select();
        jso_data($l, 200);
    }
    
    public function zhu(OrderModel $orderModel)
    {
        $data  = $this->post(['order_id']);
        $offer = $orderModel->TuiNewOffer($data['order_id']);
        jso_data($offer, 200);
    }
    
    /*
    * 更新师傅
    */
    public function mastOrder()
    {
        
        $data = Request::instance()->post();
        
        $user_arr = $data['leader'] == null ? [] : json_decode($data['leader'], true);
        $s1       = $s1 = array_column($user_arr, 'masterId');
        $s1       = implode(',', $s1);
        //            $xiu_id = $s1;
        db('startup')->where('orders_id', $data['order_id'])->update(['xiu_id' => $s1]);
        jso_data([], 200);
    }
    
    /*
    * 订单完成后返工
    */
    public function rework()
    {
        
        $data = $this->post(['order_id']);
        $o    = db('order')->where(['order_id' => $data['order_id']])->find();
        if ($o) {
            db('order')->where(['order_id' => $data['order_id']])->update(['rework' => 0]);
            jso_data([], 200);
        }
        
        jso_data([], 300, '订单不存在');
    }
    
    /*
    * 订单完工
    */
    public function finished(PollingModel $pollingModel)
    {
        $data = $this->post(['order_id']);
        db()->startTrans();
        try {
    
            $orderList    = db('order_setting')
                ->where('order_setting.order_id', $data['order_id'])
                ->find();
            if( $orderList['work_check']==1){
                $order_acceptance    = db('order_acceptance')->where('deleted_at',0)->where(['order_id'=>$data['order_id']])->count();
                if($order_acceptance==0){
                    throw  new  Exception('请联系店长添加完工验收单');
                }
            }
            /*
             * 师傅标注的节点
             */
            $capital_id            = Db::connect(config('database.db2'))->table('app_user_order_capital')->where(['order_id' => $data['order_id']])->whereNull('deleted_at')->column('capital_id');
            $auxiliary_interactive = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital_id)->where('auxiliary_project_list.order_id', $data['order_id'])->whereNull('auxiliary_project_list.delete_time')->count();
            
            $auxiliary_interactiveCount = db('auxiliary_delivery_node')->Join('auxiliary_delivery_schedule', 'auxiliary_delivery_schedule.id=auxiliary_delivery_node.auxiliary_delivery_schedul_id', 'left')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital_id)->where('auxiliary_project_list.order_id', $data['order_id'])->where('auxiliary_delivery_node.state', 1)->whereNull('auxiliary_project_list.delete_time')->column('auxiliary_delivery_node.auxiliary_delivery_schedul_id');
            
            /*
             * 所有的交付节点
             */
            $envelopes_id = db('envelopes')->where('type', 1)->where('ordesr_id', $data['order_id'])->value('envelopes_id');
            $capital      = db('capital')->where('envelopes_id', $envelopes_id)->where('types', 1)->column('capital_id');
            $auxiliary    = db('auxiliary_delivery_schedule')->Join('auxiliary_project_list', 'auxiliary_delivery_schedule.auxiliary_project_list_id=auxiliary_project_list.id', 'left')->whereIn('auxiliary_project_list.capital_id', $capital)->where('auxiliary_project_list.order_id', $data['order_id'])->whereNull('auxiliary_project_list.delete_time')->count();
            if ($auxiliary_interactive > count(array_merge(array_unique($auxiliary_interactiveCount)))) {
                throw  new  Exception('该项目还有交付标准没有上传，不能完工');
            }
            if ($auxiliary == $auxiliary_interactive) {
                db('order')->where(['order_id' => $data['order_id']])->update(['state' => 7, 'update_time' => time()]);
                
            }
            
            db()->commit();
            $finish_time = db('order')->where(['order_id' => $data['order_id'], 'state' => 7])->field('finish_time,state')->find();
            if ($finish_time['finish_time'] != 0 && $finish_time['state'] != 7) {
                $pollingModel->Alls($data['order_id'], 4, 0, time());
            }
            sendOrder($data['order_id']);
            jso_data([], 200);
        } catch (Exception $e) {
            db()->rollback();
            jso_data([], 300, $e->getMessage());
        }
    }
    
    public function update(PollingModel $pollingModel,CommonModel $common)
    {
        $data               = $this->post(['order_id', 'user_id', 'type']);
        $params = Request::instance()->post();
        $reality_artificial = Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $data['order_id']])->where('status', '<>', 10)->whereNull('deleted_at')->field('finish_at,start_at')->select();
        $mastUsername = Db::connect(config('database.db2'))->table('app_user')->where(['id' => $data['user_id']])->value('username');
        $startup= Db::table('startup')->where('orders_id', $data['order_id'])->find();
        $gong= Db::table('envelopes')->where('ordesr_id', $params['order_id'])->where('type',1)->value('gong');
        $time               = [];
        if($reality_artificial){
            foreach ($reality_artificial as $value) {
                if ($value['finish_at'] != 0) {
                    $time[] = $value['finish_at'];
                }
                if ($value['start_at'] != 0) {
                    $times[] = $value['start_at'];
                }
            }
    
            if (count($reality_artificial) == count($time)) {
                if (isset($time) && is_array($time)) {
                    $max_time    = array_search(max($time), $time);
                    $finish_time = $time[$max_time];
                } else {
                    $finish_time = 0;
                }
        
            } else {
                $finish_time = 0;
            }
            if (isset($times) && is_array($times)) {
                $max_times  = array_search(min($times), $times);
                $start_time = $times[$max_times];
            } else {
                $start_time = 0;
            }
            $new_payment = db('order_setting')->join('sign', 'sign.order_id=order_setting.order_id', 'left')->where(['order_setting.order_id' => $data['order_id']])->field('payment_type,main_mode_type1,auxiliary_interactive_id')->find();
            if ($new_payment['payment_type'] != 2) {
                if (!empty($new_payment['main_mode_type1']) && empty($new_payment['auxiliary_interactive_id']) && $data['type'] == 3) {
                    $user_ids    = Db::connect(config('database.db2'))->table('app_user_order_capital')->where(['order_id' => $data['order_id']])->where('capital_id', $new_payment['main_mode_type1'])->whereNull('deleted_at')->field('user_id')->select();
                    $user_idList = array_column($user_ids, 'user_id');
                    if (in_array($data['user_id'], $user_idList)) {
                        (new CommonModel())->PushCompletion(2, $data['order_id']);
                    }
            
                }
                $finishTime = db('order')->where(['order_id' => $data['order_id']])->field('start_time')->find();
                if ($finishTime['start_time'] == 0 && $data['type'] == 1) {
                    (new CommonModel())->PushCompletion(1, $data['order_id']);
                }
        
        
            }
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $data['order_id']])->update(['all_finish_at' => $finish_time]);
            $startTime = db('order')->where(['order_id' => $data['order_id']])->value('start_time');
            if (empty($startTime)) {
                db('order')->where(['order_id' => $data['order_id']])->update(['start_time' => $start_time]);
                $work_calendar = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d',$start_time))->where('is_work', 1)->order('data_string ACS')->limit($gong)->field('year,month,day,week,is_work,type,data_string')->select();
                if(empty($startup['sta_time'])){
                    $common->StartJournal($params['order_id'],$data['user_id'],$mastUsername,3,'师傅开工');
                    Db::table('startup')->where('orders_id', $params['order_id'])->update(['sta_time'=>$start_time,'up_time'=>strtotime($work_calendar[count($work_calendar)-1]['data_string'].' 23:59:59')]);
                }
                Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $data['order_id']])->where('plan_start_at',0)->update(['plan_start_at' => $start_time,'plan_end_at'=>strtotime($work_calendar[count($work_calendar)-1]['data_string'].' 23:59:59'),'plan_work_time'=>$gong* 24 * 60 * 60]);
                if ($start_time != 0) {
                    $pollingModel->Alls($data['order_id'], 3, 0, $start_time);
                }
                openapiAddTask($data['order_id'],6,'师傅开工','');
            }
            $finish_time = db('order')->where(['order_id' => $data['order_id'], 'state' => 7])->field('finish_time,state')->find();
            if ($finish_time['finish_time'] != 0 && $finish_time['state'] != 7) {
                $pollingModel->Alls($data['order_id'], 4, 0, $finish_time);
            }
        }
        if(isset($params['masterType']) && $params['masterType']==1){
            $time=time();
            db('order')->where(['order_id' => $data['order_id']])->update(['start_time' =>$time]);
            $work_calendar = db('work_calendar', config('database.zong'))->where('data_string', '>=', date('Y-m-d',$time))->where('is_work', 1)->order('data_string ACS')->limit($gong)->field('year,month,day,week,is_work,type,data_string')->select();
            if(empty($startup)){
                Db::table('startup')->insert(['sta_time'=>$time,'up_time'=>strtotime($work_calendar[count($work_calendar)-1]['data_string'].' 23:59:59'),'orders_id'=>$params['order_id']]);
                $common->StartJournal($params['order_id'],$data['user_id'],$mastUsername,3,'师傅开工');
            }elseif(empty($startup['sta_time'])){
                Db::table('startup')->where('orders_id', $params['order_id'])->update(['sta_time'=>$time,'up_time'=>strtotime($work_calendar[count($work_calendar)-1]['data_string'].' 23:59:59')]);
            }
            Db::connect(config('database.db2'))->table('app_user_order')->where(['order_id' => $data['order_id']])->where('plan_start_at',0)->update(['plan_start_at' => $start_time,'plan_end_at'=>strtotime($work_calendar[count($work_calendar)-1]['data_string'].' 23:59:59'),'plan_work_time'=>$gong* 24 * 60 * 60]);
            openapiAddTask($data['order_id'],6,'师傅开工','');
        }
       
        
        jso_data([], 200);
        
    }
    /*
     * 甘特图
     */
    public function ganttChart(){
        $data = input('get.orderId');
        $orderId=$data;
        if(empty($orderId)){
            jso_data(null,300,'缺少参数');
        }
        $envelopes_id=  db('envelopes')->where('ordesr_id',$orderId)->where('type',1)->value('envelopes_id');;
        $envelopes_gantt_chart=db('envelopes_gantt_chart')->where('order_id',$orderId)->where('envelopes_id', $envelopes_id)->where('id desc')->where('delete_time',0)->find();
        jso_data(json_decode($envelopes_gantt_chart['result'],true),200);
    }
    /*
    * 根据店铺查店长
    */
    public function shop()
    {
        
        $data = $this->post(['store_id']);
        
        $l = db('user')->field('user.user_id,user.username,user.mobile,st.store_name')->join('store st', 'user.store_id=st.store_id', 'left')->where('user.store_id', $data['store_id'])->select();
        
        jso_data($l, 200);
    }
    
    /**
     * 店铺详情
     * invoice_type
     */
    public function xiang_q()
    {
        $P   = Request::instance()->post('store_id');
        $res = db('store')->field('store.store_name,store.addres,pe.province,ci.city,cu.county')->join('province pe', 'pe.province_id=store.province', 'left')->join('city ci', 'ci.city_id=store.city', 'left')->join('county cu', 'cu.county_id=store.area', 'left')->where('store_id', $P)->find();
        if ($res !== false) {
            jso_data($res, 200);
        }
        jso_data([], 300);
        
        
    }
    
    /**
     * 完工时间
     */
    public function Commencement()
    {
        $data    = $this->post(['order_id']);
        $startup = db('startup')->where('orders_id', $data['order_id'])->find();
        if (empty($startup['sta_time']) && empty($startup['up_time'])) {
            $thro = db('through')->where(['order_ids' => $data['order_id'], 'baocun' => 1])->order('th_time desc')->find();
            if ($thro) {
                $ca = db('envelopes')->where(['through_id' => $thro['through_id']])->field('gong')->find();
            } else {
                $ca = db('envelopes')->where(['ordesr_id' => $data['order_id'], 'through_id' => 0])->field('gong')->find();
            }
            $da  = ['sta_time' => time(), 'up_time' => strtotime("+" . $ca['gong'] . "day", time())];
            $res = db('startup')->where('orders_id', $data['order_id'])->update($da);
            if ($res) {
                jso_data($da, 200);
            } else {
                jso_data([], 300);
            }
        }
        jso_data([], 200);
        
        
    }
    
    /**
     * 店铺
     * invoice_type
     */
    public function dian()
    {
        $res = db('store')->select();
        if ($res !== false) {
            jso_data($res, 200);
        }
        jso_data([], 300, '编辑失败，请刷新后重试');
        
        
    }
    
    /**
     * 店铺
     * invoice_type
     */
    public function pu()
    {
        $res = db('store')->select();
        if ($res !== false) {
            r_date($res, 200);
        }
        r_date([], 300, '编辑失败，请刷新后重试');
        
        
    }
    
    public function synchronization()
    {
        $data   = Request::instance()->post();
        $Client = new \app\api\model\Client();
        $Client->index($data['order_id'], $Client::exchange, $Client::queue);
        return json_encode(['code' => 200, 'msg' => '更新成功']);
    }
    
    /*
     * 师傅获取二维码
     */
    public function masterQRcode()
    {
        $data   = Request::instance()->post();
        $common = new CommonModel();
        $list   = $common->personalName($data, $data['cityId'], 2);
        jso_data($list, 200);
    }

    /*
     * 师傅端后端负责人获取施工节点
     */
    public function BackendResponsible()
    {
        $data             = Request::instance()->post();
        $ConstructionNode = new ConstructionNode();
        $change_work_time = db('order_times')->where('order_id', $data['orderId'])->value('change_work_time');
      
        if ($change_work_time > 1748534400) {
            $capital          = $ConstructionNode->Lists($data['orderId'], $data['type']);
           
        } else {
            $capital          = $ConstructionNode->List($data['orderId'], $data['type']);
        }

        jso_data($capital, 200);
    }
    
    /*
    * 师傅端后端负责人获取施工节点审核
    */
    public function BackendResponsibleToExamine()
    {
        $data             = Request::instance()->post();
        $nodeIds          = json_decode($data['nodeIds'], true);
        $nodeIds          = implode($nodeIds, ',');
        $ConstructionNode = new ConstructionNode();
        $change_work_time=db('order_times')->where('order_id',$data['orderId'])->value('change_work_time');
         if($change_work_time>1748534400){ 
             $capitalNode      = $ConstructionNode->toNewExamine($nodeIds, $data['state'], $data['reason'], $data['orderId'],$data['userId'],$data['capitalId']);
        }else{
             $capitalNode      = $ConstructionNode->toExamine($nodeIds, $data['state'], $data['reason'], $data['orderId'],$data['userId']);
        }
       
        jso_data(null, $capitalNode['code'], $capitalNode['msg']);
    }
    
    /*
   * 师傅端后端负责人工序模版
   */
    public function ProcessTemplate(WorkProcess $workProcess, QuotationListOperation $listOperation,Capital $capital)
    {
        $data = Request::instance()->post();
        if (empty($data['orderId'])) {
            jso_data([], 300, "订单id不能为空");
        }
        $template               = null;
        $list                   = $listOperation->ProcessTemplateList($data['orderId']);
        if (!empty($list['list'])) {
            $template = Db::connect('database.zong')->table('work_template')->whereIn('id', $list['list'])->where('status', 1)->field('title,id')->select();
        }
        $work_capital_type = \db('work_capital_type')->where('order_id', $data['orderId'])->select();
        $isId              = 1;
        if (!empty($work_capital_type)) {
            $isId = 1;
        }
        if(empty($template)){
            $list = $capital->workingProcedure($data['orderId']);
            if (!empty($list)) {
                $workProcessId       = array_merge(array_unique(array_column($list, 'workProcessId')));
            
                $workProcessIdString = null;
                foreach ($workProcessId as $item) {
                    if (!empty($item)) {
                        $workProcessIdString .= $item . ',';
                    }
                }
            }
            if (!empty($workProcessIdString)) {
                $WorkTemplateDetailed = $workProcess->WorkTemplateDetailed($workProcessIdString)->toArray();
            }
            if(!empty($WorkTemplateDetailed)){
                $isId = 1;
            }
        }
        jso_data(['data' => $template, 'isId' => $isId], 200);
    }

    /*
    * 师傅端后端负责人施工进度
    */
    public function ConstructionProgress(Capital $capital, WorkProcess $workProcess, QuotationListOperation $listOperation)
    {
        $data = Request::instance()->post();
        if (empty($data['orderId'])) {
            jso_data([], 300, "订单id不能为空");
        }

        $orderId = $data['orderId'];
        $list = db('order_times')->where('order_id', $orderId)->find();
        if ($list['change_work_time'] > 1748534400) {
            $finalResult = $listOperation->newConstructionProgressModel($orderId, $workProcess);
            jso_data($finalResult, 200);
        } else {
            $list = $listOperation->ConstructionProgressModel($capital, $workProcess, $data['orderId'], $data['id']);
            if ($data['isSave'] == 1 || $list['Additions'] == 1) {
                $listArray = $workProcess->saveList($list['result'], $data['orderId'], 1, $data['user_id']);
                jso_data($list['result'], $listArray['code'], $listArray['message']);
            } else {
                jso_data($list['result'], 200);
            }
        }
    }
    
    /*
   * 师傅端后端负责人据工种获取工序
   */
    public function getOperation(Capital $capital, WorkProcess $workProcess, QuotationListOperation $listOperation)
    {
        $data = Request::instance()->post();
        if ($data['id'] == 0) {
            jso_data(null, 300, '缺少参数');
        }
        $capitalList = json_decode($data['capitalList'], true);
        if (empty($capitalList)) {
            jso_data(null, 300, '缺少参数');
        }
        $result = $listOperation->getOperationModel($capital, $workProcess, $data['id'], $data['capitalList']);
        jso_data($result, 200);
    }
    
    /*
    * 师傅端后端负责人保存工序
    */
    public function workCapital(WorkProcess $workProcess,QuotationListOperation $listOperation)
    {
        $data      = Request::instance()->post();
        $list      = json_decode($data['list'], true);
         $order_time = db('order_times')->where('order_id', $data['orderId'])->find();
        if ($order_time['change_work_time'] > 1748534400) {
            $listArray = $listOperation->saveList($list, $data['orderId']);
            jso_data(null, 200);
        } else {
            $listArray = $workProcess->saveList($list, $data['orderId'], 1, $data['user_id']);
            jso_data(null, $listArray['code'], $listArray['message']);
        }
      
    }
    
    /*
    * 主材进度
     */
    public function mainMaterialProgress(QuotationListOperation $listOperation)
    {
        $data   = Request::instance()->post();
        $result = $listOperation->mainMaterialProgressModel($data['orderId']);
        jso_data($result, 200);
    }
    
    /*
    * 展示
    */
    public function ShowMaterials(Capital $capital)
    {
        $data         = Request::instance()->post();
        $config       = Db::connect(config('database.zong'))->table('sys_config')->where('keyss', 'agent_detailed_code')->find();
        $capitalCount = 0;
        if ($config) {
            $capitalCount = $capital->ShowMaterialsCspital($data['orderId'], $config['valuess']);
        }
        jso_data($capitalCount, 200);
    }
    
    /*
   * 展示
   */
    public function OssClientCopy()
    {
        $data         = Request::instance()->post();
        $aLi=new Aliyunoss();
        $path=$data['path'];
        $oldImg=$data['oldImg'];
        $l=$aLi->copyObject($path,$oldImg);
        if ($l['info']['http_code'] != 200) {
            jso_data(null, 300,'图片上传错误');
        }
        jso_data(null, 200);
    }
}
